import express from 'express';
import moment from 'moment';
import Sequelize from 'sequelize';
import { Order } from '../../modal/index'; // 数据库实体类
import { statusList, sequelizeStatus } from '../../common/status'; // 状态码对照
import { checkPermission, aesEncrypt, addMoney, sendMuban } from '../../utils/utils'; // 工具类
import baseDao from '../../lib/baseDao'; // 用于获取实例化的sequelize
import CONFIG from '../../../config/config.config'; // 全局配置

const router = express.Router();
const minLevel = 0; // 允许调用接口的最低等级

router.post('/', async function (Request, Response, next) {
  // Order.Modal.sync();
  let param = Request.body
  const transaction = await baseDao.sequelize.transaction() // 事务
  // 权限校验
  param.status = 1 // 1已结算
  await checkPermission(Request, Response, minLevel).then(res => {
    param.userId = res.id
    param.level = res.level
    param.openId = res.openId
  })

  let orders = [] // 查询到的订单列表
  await queryOrder(param.tradeParentId, transaction, Response).then(res => {
    orders = res;
  })

  let addGold = 0 // 计算出来应该增加的积分
  for (let i = 0; i < orders.length; i++) {
    let item = orders[i]
    let returnGold = Math.ceil(item.totalCommissionFee * 10 * CONFIG.levelEarning * param.level)
    let bindParam = {
      userId: param.userId,
      status: 1,
      returnGold: returnGold,
      tradeParentId: item.tradeParentId,
      tradeId: item.tradeId,
    }
    await bindOrder(bindParam, transaction, Response).then(res => {
      addGold += returnGold;
    })
  }

  let addParam = {
    userId: param.userId,
    title: '下单返还积分',
    addGold: addGold, // 要加的积分
  }
  await addMoney(addParam, transaction, Response).then(async res => {
    console.log('增加成功，当前积分：', res)
  })

  await transaction.commit() // 提交事务
  if (param.formId) {
    let mubanParam = {
      page: param.page, // 点击模板跳转页面
      formId: param.formId,
      openId: param.openId,
      templateId: CONFIG.bindOrderId, // 绑定成功通知ID
      data: {
        keyword1: {
          value: '恭喜，您输入的订单绑定成功'
        },
        keyword2: {
          value: moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        },
        keyword3: {
          value: `用户积分+${addParam.addGold}`
        },
      }
    }
    sendMuban(mubanParam, Response) // 发送模板消息
  }
  Response.json({
    data: {
      addGold: addGold,
    },
    message: "success"
  });
});

function queryOrder(tradeParentId, transaction, Response) {
  // 获取淘礼金URL
  return new Promise((resolve, reject) => {
    Order.Modal.findAll({
      where: {
        tradeParentId: tradeParentId,
        status: 0, // 0未结算
      },
      raw: true, // 返回标准json格式
    }).then(async res => {
      if (res && res.length > 0) {
        resolve(res)
      } else {
        await transaction.rollback() // 回滚
        Response.status(300).send({ message: "抱歉，当前该订单号不存在" });
      }
    }).catch(async err => {
      console.log(err)
      await transaction.rollback() // 回滚
      Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
    });
  })
}

function bindOrder(bindParam, transaction, Response) {
  // 获取淘礼金URL
  return new Promise((resolve, reject) => {
    Order.Modal.update({
      userId: bindParam.userId,
      status: bindParam.status,
      returnGold: bindParam.returnGold
    }, {
        where: {
          tradeParentId: bindParam.tradeParentId,
          tradeId: bindParam.tradeId,
        },
        transaction: transaction
      }).then(async res => {
        console.log(bindParam)
        if (res && res.length > 0) {
          resolve(res[0])
        } else {
          await transaction.rollback() // 回滚
          Response.status(300).send({ message: "绑定订单记录失败" });
        }
      }).catch(async err => {
        console.log(err)
        await transaction.rollback() // 回滚
        Response.status(500).send({ message: sequelizeStatus[err.name] || statusList[500] || err.name });
      });
  })
}

module.exports = router;